package bold.deposit.useful;

import bold.storage.core.Page;
import bold.storage.core.Record;
import bold.storage.core.RecordList;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用消息封装
 * 静态代码块执行 map 初始化 不需要 用枚举类  或者 内部枚举类
 * code  200 400 404 401没登录 402登录失效 500以上为系统内部错误
 * msg   消息提示
 * error 错误提示(不展示给用户)
 */
public class Result extends HashMap<String, Object> {
    public static final Map<Integer, String> map;

    static {
        map = new HashMap<>(5);
        map.put(200, "操作成功");
        map.put(400, "参数错误");
        map.put(404, "暂无数据");
        map.put(402,"无权限");
    }

    public static Result Empty = new Result(404);

    public Result() {
        super(5);
    }

    public Result(int code) {
        setCode(code);
        setMsg(map.get(code));
    }

    public Result(int code, String msg) {
        setCode(code);
        setMsg(msg);
    }

    public Result(int code, final Object obj) {
        put("code", code);
        put("data", obj);
    }

    public Result(boolean obj) {
        if (obj) {
            setCode(200);
            setMsg(map.get(200));
            putData(obj);
        } else {
            setCode(404);
            setMsg(map.get(404));
        }
    }

    public Result(final Object obj) {
        setCode(200);

        if (obj == null) {
            setCode(404);
            setMsg(map.get(404));
            return;
        }

        if (obj instanceof Page) {
            if (((Page) obj).getTotalRow() <= 0) {
                setCode(404);
                setMsg(map.get(404));
            } else {
                putData(obj);
            }
            return;
        }

        if (obj instanceof Record) {
            if (((Record) obj).isEmpty()) {
                setCode(404);
                setMsg(map.get(404));
            } else {
                putData(obj);
            }
            return;
        }

        if (obj instanceof HashMap) {
            if (((HashMap) obj).isEmpty()) {
                setCode(404);
                setMsg(map.get(404));
            } else {
                putData(obj);
            }
            return;
        }

        if (obj instanceof RecordList) {
            if (((RecordList) obj).size() <= 0) {
                setCode(404);
                setMsg(map.get(404));
            } else {
                putData(obj);
            }
            return;
        }
        setMsg(map.get(200));
        putData(obj);
    }

    public Result putData(Object value) {
        put("data", value);
        return this;
    }

    public Result setMsg(String msg) {
        put("msg", msg);
        return this;
    }

    public Result setError(String msg) {
        put("error", msg);
        return this;
    }

    public Result setCode(int code) {
        put("code", code);
        return this;
    }

    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

}